<template>
  <div>
    <el-upload
        drag
        :accept="accept"
        :auto-upload="true"
        :http-request="checkedFile"
        :before-remove="removeFile"
        :limit="10"
        action="/"
        :show-file-list="false"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
  </div>


</template>
<script>
	import axios from 'axios'
export default {
  props: {
    categoryId: {
      type: [String, Number],
      default: 0
    },
    accept: {
      type: [String, Number],
      default: "."
    }
  },
  data() {
    return {
      isUpload: true,
      maxSize: 5 * 1024 * 1024 * 1024, // 上传最大文件限制
      multiUploadSize: 50 * 1024 * 1024, // 大于这个大小的文件使用分块上传(后端可以支持断点续传)
      eachSize: 10 * 1024 * 1024, // 每块文件大小
      requestCancelQueue: [], // 请求方法队列（调用取消上传
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const fileName = file.name;
      const extname = fileName.substr(fileName.lastIndexOf(".")).toLowerCase();
      return this.getFileType(extname);
    },
    getFileType(extname) {
      let fileType = null;
      let video = ['.mp4', '.3gp', '.asf', '.wmv', '.avi', '.mkv', '.rmvb', '.flv', '.ogg', '.amr'];
      let picture = ['.jpg', '.jpeg', '.png', '.gif', '.svg'];
      let music = ['.mp3', '.wav'];
      let document = ['.doc', 'docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.pdf', '.zip', '.rar', '.csv', '.sql'];

      if (video.includes(extname)) {
        fileType = 'video'
      }
      if (picture.includes(extname)) {
        fileType = 'picture'
      }
      if (music.includes(extname)) {
        fileType = 'music'
      }
      if (document.includes(extname)) {
        fileType = 'document'
      }
      return fileType;
    },
    async checkedFile(options) {


      const {maxSize, multiUploadSize, getSize, singleUpload} = this
      const {file, onProgress, onSuccess, onError} = options

      console.log("获取文件", this.beforeAvatarUpload(file))
      //判断是否可以上传
      if (!this.beforeAvatarUpload(file)) {
        this.$message({
          message: `上传的文件格式不支持`,
          type: 'error'
        })
        onError()
        return
      }

      if (file.size > maxSize) {
        this.$message({
          message: `您选择的文件大于${getSize(maxSize)}`,
          type: 'error'
        })
        onError()
        return
      }
      console.log("大文件", file.size > multiUploadSize)

      const uploadFunc = singleUpload
      try {
        await uploadFunc(file, onProgress)
        this.$message({
          message: '上传成功',
          type: 'success'
        })
        onSuccess()
      } catch (e) {
        console.error(e)
        this.$message({
          message: e.message,
          type: 'error'
        })
        onError()
      }
      const prom = new Promise((resolve, reject) => {
      })
      prom.abort = () => {
      }
      return prom
    },
    // 格式化文件大小显示文字
    getSize(size) {
      return size > 1024
          ? size / 1024 > 1024
              ? size / (1024 * 1024) > 1024
                  ? (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
                  : (size / (1024 * 1024)).toFixed(2) + 'MB'
              : (size / 1024).toFixed(2) + 'KB'
          : (size).toFixed(2) + 'B'
    },
    /**
     * 单文件直接上传
     * @param file
     * @param onProgress
     * @returns {Promise<axios.AxiosResponse<any>> | *}
     */
    singleUpload(file, onProgress) {
      return this.postFile({file, uid: file.uid, categoryId: this.categoryId, fileName: file.name}, onProgress)
    },

    removeFile(file) {
      this.requestCancelQueue[file.uid]()
      delete this.requestCancelQueue[file.uid]
      return true
    },
    // 提交文件方法,将参数转换为FormData, 然后通过axios发起请求
    postFile(param) {
      const formData = new FormData()
      for (let p in param) {
        formData.append(p, param[p])
      }
	  const token = localStorage.getItem('token')
      return axios.post('http://api.shop.vue-os.com/api/files/upload',formData, {
		  headers:{
			  Authorization: "Bearer " + token
		  },
	  }).then(rs => {
        console.log('res',rs)
        this.$emit('complete',rs.data.data.url)
      })
    },
  }
}
</script>
